package com.bmps.springcloud.insuredmicroservice.service.cloudplatform;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bmps.springcloud.common.config.RiskUrlConfig;
import com.bmps.springcloud.common.response.CloudPlatModel;
import com.bmps.springcloud.common.response.CommandReturnModel;
import com.bmps.springcloud.common.response.TaskResponseModel;
import com.bmps.springcloud.insuredmicroservice.constant.accept.AcceptConstant;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;
import java.util.*;

/**
 * 调用保盾云
 * @author llz
 * @date 2019/08/16
 */
@Service
public class RiskSupport {
    private static Logger logger = LoggerFactory.getLogger(RiskSupport.class);

    private final RestTemplate restTemplate;

    //private final CloudRiskSupportRepository cloudRiskSupportRepository;

    private final RiskUrlConfig riskUrlConfig;

    public RiskSupport(RestTemplate restTemplate,
                       //CloudRiskSupportRepository cloudRiskSupportRepository,
                       RiskUrlConfig riskUrlConfig) {
        this.restTemplate = restTemplate;
        //this.cloudRiskSupportRepository = cloudRiskSupportRepository;
        this.riskUrlConfig = riskUrlConfig;
    }

    private JSONObject postUrlOld(String url, String requestParameter) {
        HttpHeaders headers = new HttpHeaders();
        headers.set("Content-Type", "application/json; charset=utf-8");
        HttpEntity<String> formEntity = new HttpEntity<>(requestParameter, headers);
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, formEntity, String.class);
        String responseStr = responseEntity.getBody();
        return (JSONObject) JSONObject.parse(responseStr);
    }

    public TaskResponseModel riskInvokeOld(String key, CloudPlatModel cloudPlatModel) {
        List<CloudPlatModel> cloudPlatModelList = new ArrayList<>();
        TaskResponseModel taskResponseModel = new TaskResponseModel();
        taskResponseModel.setKey(key);
        taskResponseModel.setResultCode(AcceptConstant.RESULT_SUCCESS_CODE);
        taskResponseModel.setResultMessage(AcceptConstant.RESULT_SUCCESS_MESSAGE);
        JSONObject jsonObject;
        String requestParameter = JSONObject.toJSONString(cloudPlatModel);
        try {
            jsonObject = postUrlOld(riskUrlConfig.getUrl(), requestParameter);
        } catch (Exception e) {
            cloudPlatModel.setResultCode(0);
            cloudPlatModel.setResult(0.0);
            cloudPlatModelList.add(cloudPlatModel);
            taskResponseModel.setCloudPlatModelList(cloudPlatModelList);
            logger.error("保盾云调用异常返回结果："+e.getMessage()+"请求报文：" + cloudPlatModel.toString());
            return taskResponseModel;
        }
        logger.error("请求保盾云参数："+requestParameter+"保盾云返回结果："+jsonObject.toJSONString());
        dealResultOld(jsonObject, cloudPlatModel, taskResponseModel);
        return taskResponseModel;
    }

    private void dealResultOld(JSONObject jsonObject, CloudPlatModel cloudPlatModel, TaskResponseModel taskResponseModel) {
        List<CloudPlatModel> cloudPlatModelList = new ArrayList<>();
        int status = Integer.valueOf(jsonObject.get("status").toString());
        cloudPlatModel.setTimestamp(jsonObject.get("timestamp").toString());
        if(status != 0) {
            cloudPlatModel.setResultCode(2);
            cloudPlatModel.setResult(0.0);
            logger.info("保盾云没有获取到正确的信息："+jsonObject.get("error").toString()+";返回信息："+jsonObject.toString());
        }else {
            double info = Double.valueOf(jsonObject.get("info").toString());
            cloudPlatModel.setResultCode(1);
            cloudPlatModel.setResult(info);
        }
        cloudPlatModelList.add(cloudPlatModel);
        taskResponseModel.setCloudPlatModelList(cloudPlatModelList);
    }

    private List<CommandReturnModel> postUrl(String url, String requestParameter) {
        HttpHeaders headers = new HttpHeaders();
        headers.set("Content-Type", "application/json; charset=utf-8");
        HttpEntity<String> formEntity = new HttpEntity<>(requestParameter, headers);
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, formEntity, String.class);
        JSONArray array = JSONArray.parseArray(responseEntity.getBody());
        String str = Objects.requireNonNull(JSON.toJSON(array)).toString();
        return JSONObject.parseArray(str, CommandReturnModel.class);
    }

    public TaskResponseModel riskInvoke(String key, HashSet<CloudPlatModel> cloudPlatModelHashSet) {
        TaskResponseModel taskResponseModel = new TaskResponseModel();
        taskResponseModel.setKey(key);
        taskResponseModel.setResultCode(AcceptConstant.RESPONSE_SUCCESS_CODE);
        taskResponseModel.setResultMessage(AcceptConstant.RESULT_SUCCESS_MESSAGE);
        List<CloudPlatModel> cloudPlatModelList = new ArrayList<>(cloudPlatModelHashSet);
        String requestParameter = JSONObject.toJSONString(cloudPlatModelHashSet);
        List<CommandReturnModel> commandReturnModelList ;
        try {
            commandReturnModelList = postUrl(riskUrlConfig.getUrl(), requestParameter);
        } catch (Exception e) {
            for (CloudPlatModel cloudPlatmodel : cloudPlatModelList) {
                cloudPlatmodel.setResultCode(0);
                cloudPlatmodel.setResult(0.0);
                cloudPlatmodel.setErrorMessage("调用超时!");
                //cloudRiskSupportRepository.insertRiskSupport(cloudPlatmodel.getPolicyno(), cloudPlatmodel.getResultCode(), cloudPlatmodel.toString(), " 保盾云调用失败！");
            }
            taskResponseModel.setCloudPlatModelList(cloudPlatModelList);
            logger.error("调用异常："+e.getMessage()+"请求报文：" +cloudPlatModelHashSet.toString());
            return taskResponseModel;
        }
        dealResult(commandReturnModelList, cloudPlatModelList,taskResponseModel);
        logger.info("返回结果：" + taskResponseModel.toString());
        return taskResponseModel;
    }

    private void dealResult(List<CommandReturnModel> commandReturnModelList, List<CloudPlatModel> cloudPlatModelList,TaskResponseModel taskResponseModel) {

        if (commandReturnModelList.size() == 1 && commandReturnModelList.get(0).getKey().contains("error")) {
            for (CloudPlatModel cloudPlatModel : cloudPlatModelList) {
                cloudPlatModel.setResultCode(2);
                cloudPlatModel.setResult(0.0);
                cloudPlatModel.setErrorMessage("并发线程调用失败，所有的都通过!");
                cloudPlatModel.setStatus(commandReturnModelList.get(0).getStatus());
                //cloudRiskSupportRepository.insertRiskSupport(cloudPlatModel.getPolicyno(), cloudPlatModel.getResultCode(), commandReturnModelList.toString(), "并发线程调用失败，所有的都通过");
            }
            logger.info("保盾云并发线程调用失败，错误信息："+commandReturnModelList.get(0).getData()+"；返回结果："+commandReturnModelList.toString());
        }else {
            for (CommandReturnModel commandReturnModel : commandReturnModelList) {
                JSONObject data = JSONObject.parseObject(commandReturnModel.getData());
                if (commandReturnModel.getKey().startsWith("baodunyun|")) {
                    String[] keyValue = (commandReturnModel.getKey()).split("\\|");
                    if (commandReturnModel.getStatus() == 900) {
                        for (CloudPlatModel cloudPlatModel : cloudPlatModelList) {
                            if (StringUtils.equals(keyValue[1], cloudPlatModel.getId())) {
                                cloudPlatModel.setResultCode(2);
                                cloudPlatModel.setResult(0.0);
                                cloudPlatModel.setStatus(commandReturnModel.getStatus());
                                cloudPlatModel.setErrorMessage(commandReturnModel.getData());
                                //传出data
                                //cloudRiskSupportRepository.insertRiskSupport(cloudPlatModel.getPolicyno(), cloudPlatModel.getResultCode(), commandReturnModel.getData(), "保盾云没有调用成功！");
                                break;
                            }
                        }
                    }
                    if (commandReturnModel.getStatus() == 0) {
                        for (CloudPlatModel cloudPlatModel : cloudPlatModelList) {
                            if (StringUtils.equals(keyValue[1], cloudPlatModel.getId())) {
                                cloudPlatModel.setResultCode(1);
                                cloudPlatModel.setStatus(commandReturnModel.getStatus());
                                cloudPlatModel.setSerialNo(data.get("serialNo").toString());
                                cloudPlatModel.setTimestamp(data.get("timestamp").toString());
                                cloudPlatModel.setResult(Double.valueOf(data.get("info") == null ? "0" : data.get("info").toString()));
                                //cloudRiskSupportRepository.insertRiskSupport(cloudPlatModel.getPolicyno(), cloudPlatModel.getResultCode(), commandReturnModel.toString(), "保盾云调用成功！");
                                break;
                            }
                        }
                    }
                }
            }
        }
        taskResponseModel.setCloudPlatModelList(cloudPlatModelList);
    }

}

